package com.zyp.jobseeker.controller;

import com.zyp.jobseeker.entity.Application;
import com.zyp.jobseeker.enums.ApplicationStatus;
import com.zyp.jobseeker.entity.Interview;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.service.ApplicationService;
import com.zyp.jobseeker.utils.ResultUtil;
import com.zyp.jobseeker.utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/applications")
@PreAuthorize("hasAuthority('STUDENT') or hasAuthority('ENTERPRISE')")  // 学生/企业权限
public class ApplicationController {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationController.class);

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 提交求职申请
     */
    @PostMapping("/submit")
    public ResultUtil<Map<String, Object>> submitApplication(
            @RequestHeader("Authorization") String token,
            @RequestBody Application application) {
        try {
            logger.info("[求职申请] 收到求职申请提交请求，positionId: {}", application.getPositionId());
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            // 验证token有效性
            if (!jwtUtil.isValidJwtFormat(token)) {
                logger.warn("[求职申请] ❌ 无效的JWT格式");
                return ResultUtil.fail(401, "无效的JWT格式");
            }

            if (jwtUtil.isTokenExpired(token)) {
                logger.warn("[求职申请] ❌ Token已过期");
                return ResultUtil.fail(401, "Token已过期");
            }

            // 获取用户信息
            Long studentId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.STUDENT.getCode()) {
                logger.warn("[求职申请] ❌ 权限不足: 非学生角色");
                return ResultUtil.fail(403, "仅学生可提交求职申请");
            }

            // 验证positionId是否提供
            if (application.getPositionId() == null) {
                logger.warn("[求职申请] ❌ 未提供positionId");
                return ResultUtil.fail(400, "请提供岗位ID");
            }

            // 设置申请信息
            application.setStudentId(studentId);
            application.setStatus(ApplicationStatus.PENDING);

            // 调用服务层
            Long applicationId = applicationService.submitApplication(application);
            logger.info("[求职申请] ✅ 求职申请提交成功，申请ID: {}", applicationId);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("id", applicationId);
            result.put("studentId", studentId);
            result.put("enterpriseId", application.getEnterpriseId());
            result.put("positionId", application.getPositionId());
            result.put("applyTime", application.getApplyTime());
            result.put("status", application.getStatus() != null ? application.getStatus().name() : null);
            result.put("remark", application.getRemark());

            return ResultUtil.success(result);

        } catch (IllegalArgumentException e) {
            logger.error("[求职申请] ❌ 提交失败: {}", e.getMessage());
            return ResultUtil.fail(400, "提交求职申请失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("[求职申请] ❌ 提交失败", e);
            return ResultUtil.fail(500, "提交求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 查询企业收到的求职申请
     */
    @GetMapping("/enterprise")
    public ResultUtil<PageInfo<Map<String, Object>>> getApplicationsByEnterprise(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("[求职申请] 收到企业求职申请查询请求，参数: status={}, page={}, size={}",
                    status, page, size);
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[求职申请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取企业ID
            Long enterpriseId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.ENTERPRISE.getCode()) {
                logger.warn("[求职申请] ❌ 非企业用户尝试访问企业接口");
                return ResultUtil.fail(403, "仅企业可查看收到的求职申请");
            }

            // 调用服务层
            PageInfo<Map<String, Object>> applications = applicationService.getApplicationsByEnterprise(
                    enterpriseId, status, page, size);

            logger.info("[求职申请] ✅ 查询完成，返回结果数: {}", applications.getTotal());
            return ResultUtil.success(applications);

        } catch (Exception e) {
            logger.error("[求职申请] ❌ 查询失败", e);
            return ResultUtil.fail(500, "查询求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 拒绝求职申请
     */
    @PutMapping("/{id}/reject")
    public ResultUtil<String> rejectApplication(
            @RequestHeader("Authorization") String token,
            @PathVariable Long id) {
        try {
            logger.info("[求职申请] 收到拒绝申请请求，申请ID: {}", id);
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[求职申请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long enterpriseId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.ENTERPRISE.getCode()) {
                logger.warn("[求职申请] ❌ 非企业用户尝试拒绝申请");
                return ResultUtil.fail(403, "仅企业可拒绝求职申请");
            }

            // 调用服务层
            boolean result = applicationService.rejectApplication(id);

            if (result) {
                logger.info("[求职申请] ✅ 申请拒绝成功，申请ID: {}", id);
                return ResultUtil.success("已拒绝该申请");
            } else {
                logger.warn("[求职申请] ❌ 申请拒绝失败，申请ID: {}", id);
                return ResultUtil.fail(500, "拒绝求职申请失败");
            }

        } catch (Exception e) {
            logger.error("[求职申请] ❌ 拒绝失败", e);
            return ResultUtil.fail(500, "拒绝求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 接受求职申请并生成面试邀请
     */
    @PostMapping("/{id}/accept")
    public ResultUtil<Map<String, Object>> acceptApplication(
            @RequestHeader("Authorization") String token,
            @PathVariable Long id,
            @RequestBody Interview interview) {
        try {
            logger.info("[求职申请] 收到接受申请请求，申请ID: {}", id);
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[求职申请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long enterpriseId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.ENTERPRISE.getCode()) {
                logger.warn("[求职申请] ❌ 非企业用户尝试接受申请");
                return ResultUtil.fail(403, "仅企业可接受求职申请");
            }

            // 设置面试信息
            interview.setEnterpriseId(enterpriseId);
            interview.setApplicationId(id);

            // 调用服务层
            Map<String, Object> result = applicationService.acceptApplication(id, interview);

            logger.info("[求职申请] ✅ 申请接受成功，生成面试ID: {}",
                    ((Map<String, Object>) result.get("interview")).get("id"));
            return ResultUtil.success(result);

        } catch (Exception e) {
            logger.error("[求职申请] ❌ 接受失败", e);
            return ResultUtil.fail(500, "接受求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 查询学生自己的求职申请
     */
    @GetMapping("/student")
    public ResultUtil<PageInfo<Map<String, Object>>> getApplicationsByStudent(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("[求职申请] 收到学生求职申请查询请求，参数: status={}, page={}, size={}",
                    status, page, size);
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[求职申请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long studentId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.STUDENT.getCode()) {
                logger.warn("[求职申请] ❌ 非学生用户尝试查询学生申请");
                return ResultUtil.fail(403, "仅学生可查询求职申请");
            }

            // 调用服务层
            PageInfo<Map<String, Object>> applications = applicationService.getApplicationsByStudent(
                    studentId, status, page, size);

            logger.info("[求职申请] ✅ 查询完成，返回结果数: {}", applications.getTotal());
            return ResultUtil.success(applications);

        } catch (Exception e) {
            logger.error("[求职申请] ❌ 查询失败", e);
            return ResultUtil.fail(500, "查询求职申请失败: " + e.getMessage());
        }
    }
}